<?php

namespace App\Http\Controllers\Reservation;

use App\Http\Controllers\ApiController;
use App\Transformers\Reservation\MessageTransformer;
use Carbon\Carbon;
use Illuminate\Http\Request;

class MessageController extends ApiController
{
    public function index(Request $request)
    {
        $notifications = \Auth::user()->notifications();

        $start = $request->input('start_time');
        $end   = $request->input('end_time');

        if ($start && is_null($end)) {
            $notifications->where('created_at', '>=', Carbon::parse($start)->startOfDay());
        } elseif ($end && is_null($start)) {
            $notifications->where('created_at', '<=', Carbon::parse($end)->endOfDay());
        } elseif ($start && $end) {
            $start = Carbon::parse($start)->startOfDay();
            $end   = Carbon::parse($end)->endOfDay();

            $notifications->whereBetween('created_at', [$start, $end]);
        }

        \Auth::user()->unreadNotifications()
             ->update(['read_at' => Carbon::now()->toDateTimeString()]);

        return $this->paginate($notifications->paginate(), new MessageTransformer());
    }

    protected function readAll()
    {
        $result = \Auth::user()->unreadNotifications()
                       ->update(['read_at' => Carbon::now()->toDateTimeString()]);

        return $this->responseForUpdate($result);
    }

    public function read(Request $request)
    {
        $result = \Auth::user()->notifications()->whereIn('id', $request->request->get('ids'))
                       ->update(['read_at' => Carbon::now()->toDateTimeString()]);

        return $this->responseForUpdate($result);
    }

    public function unread()
    {
        $result = \Auth::user()->unreadNotifications()->count();

        return $this->hasData(['count' => $result]);
    }
}
